<template>
  <TreeSelect
        ref="treeSelect"
        :props="props" :data="menus"
              :expand-on-click-node="false"
              :show-checkbox="false"
              @node-click="check"
  >

  </TreeSelect>
</template>

<script>
import {menuTree} from "api/admin/menu";
import ApiResponse from "utils/ApiResponse";
import http from "network/http";
export default {
  name: "MenuTreeSelect" ,
  props:{
    url: {
      type:String ,
      required: true
    },
    value: {
      type: [String , Number , Array] ,
      default: -1
    },
  } ,
  data(){
    return {
      props:{
        children: 'children',
        label: 'name'
      },
      menus: [] ,
    }
  },
  mounted() {
    this.getMenuTree() ;
  },
  watch:{
    value(){
      this.showValue()
    }
  },
  methods:{
    getMenuTree(){
       http({
        url: this.url ,
        method: 'POST' ,
        data: {
          model: {} ,
          current: 1 ,
          size: 1000
        }
      }).then(res=>{
        ApiResponse.init(res).ok((data)=>{
          this.menus = data.rows ;
          this.showValue()
        })
      })
    },
    showValue(){
      let name = "根目录" ;
      if(this.value){
        let queue = this.menus.concat([])
        while(queue.length >0){
          let menu = queue.pop();
          if(menu.menuId === this.value){
            name = menu.name ;
            break ;
          }
          if(menu.children && menu.children.length > 0){
            queue.push(...menu.children)
          }
        }
      }
      this.$refs.treeSelect.setText(name) ;
    },
    check(data){
      this.$refs.treeSelect.close() ;
      this.$emit("input",data.menuId)
      this.$refs.treeSelect.setText(data.name) ;
    }
  }
}
</script>
<style scoped>

</style>